package main

import (
	rentalpb "car_rental/rental/api/gen/v1"
	"car_rental/rental/trip"
	"car_rental/rental/trip/client/car"
	"car_rental/rental/trip/client/point"
	"car_rental/rental/trip/client/profile"
	"car_rental/rental/trip/dao"
	"car_rental/shared/server"
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"log"
)

const (
	mongoURL      = "mongodb://root:123456@localhost:47017/?authSource=car_rental&readPreference=primary&ssl=false"
	mongoDatabase = "car_rental"
)

func main() {

	logger, err := zap.NewDevelopment()

	if err != nil {
		log.Fatalf("创建zap.logger失败: %v", err)
	}

	mc := connectMongoDB(err, logger)

	logger.Sugar().Fatal(server.RunGrpcServer(&server.Config{
		AuthPublicKeyFile: "auth/rsa/rsa_public_key.pem",
		Name:              "rental",
		Addr:              "localhost:8082",
		RegisterFunc: func(s *grpc.Server) {
			rentalpb.RegisterTripServiceServer(s, &trip.Service{
				Logger:         logger,
				CarManager:     &car.Manager{},
				ProfileManager: &profile.Manager{},
				PointManger:    &point.Manager{},
				Mongo:          dao.NewMongo(mc.Database(mongoDatabase)),
			})
		},
		Logger: logger,
	}))

}

// 连接MongoDB
func connectMongoDB(err error, logger *zap.Logger) *mongo.Client {

	c := context.Background()

	mc, err := mongo.Connect(c, options.Client().ApplyURI(mongoURL))

	if err != nil {
		logger.Fatal("无法连接mongodb: %v", zap.Error(err))
	}

	return mc

}
